<?php

namespace Fwadmin\Controller;

use Common\Controller\FwadminController;
use Fwadmin\Model\MemberModel;
use Fwadmin\Model\MemberYhqModel;
use Fwadmin\Model\MemberLevelModel;

class MemberYhqController extends FwadminController {

    /**
     * 已发放优惠券
     */
    public function index() {
        
        $MemberYhqObj = new MemberYhqModel();
       
        $conditions = array();
        $param = array('username'=>'username','time_begin'=>'time_begin','time_end'=>'time_end','remark' => 'remark','is_use' => 'is_use');
        $this->paramValue($conditions, $param);
        $results = $MemberYhqObj->search($conditions);
       
        $lists = $results['list'];
        $this->assign('list', $lists); // 赋值数据集
        $this->assign('page', $results['page']); // 赋值分页输出
        
        $this->display();
    }
    
    /**
     * 发放优惠券
     */
    public function add() {
        if(IS_POST) {
            $give_type = I('post.give_type','');
            $level_ids = I('post.level_ids');
            $member_list = I('post.member_list','');
            $money = I('post.money','');
			$cart_total = I('post.cart_total','');
            $begin_time = I('post.begin_time','');
            $end_time = I('post.end_time','');
            $remark = I('post.remark','');
            $map['status'] = 1;//只发放正常会员
            $MemberObj = new MemberModel();
            $MemberYhqObj = new MemberYhqModel();
            if($give_type == "level") {//按会员等级
                $level_ids_str = implode(',', $level_ids);
                $map['level_id'] = array('in',$level_ids_str);
            } elseif($give_type == "single") {//指定会员
                $map['phone|email'] = array('in',$member_list);
            }
            $member_list = $MemberObj->field('member_id')->where($map)->select();
            $count = 0;
            foreach($member_list as $k => $v) {
                $flag =  $MemberYhqObj->add_record($v['member_id'], $money, $begin_time, $end_time,$remark,$cart_total);
                if($flag > 0) $count++;
            }
            $this->success('发送优惠券'.$count.'个成功！');
            
            
        } else {
            //会员等级
            $MemberLevelObj = new MemberLevelModel();
            $levels = $MemberLevelObj->getSel();
            $this->level_sel = $levels;

            $this->display();
        }
    }
    
     /**
     * 批量删除优惠券
     * @return int 返回删除数目
     */
    public function delsel() {
        $MemberYhqObj = new MemberYhqModel();
        $selid = I('post.selid');
        $count = 0;
        foreach($selid as $id) {
            $count += $MemberYhqObj->delete($id);
        }
        if($count > 0) {
            $this->success('删除'.$count.'优惠券成功');
        } else {
            $this->success('删除失败');
        }
    }

    

}
